package com.sky.cqculture.Contraller;

import com.sky.cqculture.pojo.HeritageItem;
import com.sky.cqculture.pojo.Category;
import com.sky.cqculture.pojo.Result;
import com.sky.cqculture.service.CategoryService;
import com.sky.cqculture.service.HeritageItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/heritage")
public class HeritageController {

    @Autowired
    private HeritageItemService heritageItemService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/items")
    public Result getAllHeritageItems() {
        List<HeritageItem> items = heritageItemService.findAllHeritageItems();
        return Result.success(items);
    }

    @GetMapping("/items/category/{categoryId}")
    public Result getHeritageItemsByCategory(@PathVariable Integer categoryId) {
        List<HeritageItem> items = heritageItemService.findHeritageItemsByCategoryId(categoryId);
        return Result.success(items);
    }

    @GetMapping("/items/search")
    public Result searchHeritageItems(@RequestParam String keyword) {
        List<HeritageItem> items = heritageItemService.searchHeritageItems(keyword);
        return Result.success(items);
    }

    @GetMapping("/items/{id}")
    public Result getHeritageItemDetail(@PathVariable Integer id) {
        HeritageItem item = heritageItemService.findHeritageItemById(id);
        return item != null ? Result.success(item) : Result.error("未找到该非遗项目");
    }

    @GetMapping("/categories")
    public Result getAllCategories() {
        List<Category> categories = categoryService.findAllCategories();
        return Result.success(categories);
    }

    @PostMapping("/items/{id}/update")
    public Result updateHeritageItemDetail(@PathVariable Integer id, @RequestBody HeritageItem heritageItem) {
        // 设置项目
        heritageItem.setId(id);
        // 调用服务层更新方法
        boolean success = heritageItemService.updateHeritageItem(heritageItem);
        return success ? Result.success() : Result.error("更新失败");
    }
}
